from django.http import HttpResponse,HttpResponseNotFound,Http404
from django.shortcuts import render_to_response
from django import forms
from django.utils import simplejson
from versionSync import Settings,pimFinder,pimParser,pimRestorer
import os
import json
import string
##@author Alessio Di Pietro
#@author Irene Scionti
#@brief restore a single entry
# @param entry_uid entry uid
# @param entry_revision revision to be restored
# @param entry_type entry type
def ajax_restore(request,entry_uid,entry_revision,entry_type):
    #get vsync settings
    settings=Settings.Settings('/etc/vsync/settings.xml')
    settings.parseSettings();
    print "restoring..."
    #restore the entry
    pimrestorer=pimRestorer.pimRestorer(settings)
    errors=pimrestorer.restore(str(entry_uid), entry_revision, int(entry_type))
    #return any error
    return HttpResponse(errors);
## @brief wrapper method for pimparser.cleaners
# @param entry_type entry_type
# @param body body to be cleaned
# @param pimparser pimparser object
def cleaners(entry_type,body,pimparser):
    if entry_type==0:
        return pimparser.vcard_body_cleaner(body);
        
    else:
        return pimparser.ics_body_cleaner(body);

## @brief find entries
# @param key searching key
# @param entry_type entry type
# @param entry_field searching field  
def ajax_find(request,key,entry_type,entry_field):
    #labels for json format
    json_labels=['uid','rev','body','state','timestamp','removed_timestamp']
    #get vsync settings
    settings=Settings.Settings('/etc/vsync/settings.xml')
    settings.parseSettings();
    pimparser=pimParser.pimParser(settings)
    if entry_field!="dtstart":
        #clean the key for date search
        key=string.replace(key, "-", "-\\")
        key=string.replace(key,"+","+\\")
    else:
        key=string.replace(key,"-","")
    if int(entry_type)==0:
        #contact tag
        field=pimParser.vcard_tags.tags[entry_field]
    else:
        #ics tag
        field=pimParser.ics_tags.tags[entry_field]
    pimfinder=pimFinder.pimFinder(settings)
    #execute searching
    found=pimfinder.find(unicode(key),int(entry_type),field)
    
    #create a json object from found list
    json_found=[[0]*5]*len(found)
    for i in range(len(found)):
        json_entry={}
        for j in range(6):
            #json_entry[json_labels[j]]=found[i][j]
            
            if j==2:
                #clean entry body
                json_entry[json_labels[j]]=cleaners(int(entry_type),(found[i][j]).encode('utf-8'),pimparser)
            else:
                json_entry[json_labels[j]]=found[i][j]
            
        json_found[i]=json_entry
    #return json object
    return HttpResponse(simplejson.dumps(json_found),mimetype='application/json')
## @brief find webapp
def find(request):
    if request.method == 'POST': # If the form has been submitted...
        form = findForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            return HttpResponse('<html><body><p>ok</p></body></html>')
    else:
        form = findForm() # An unbound form
    return render_to_response('findform.html', {
        'form': form,
    })




## @class findForm 
#@brief create the find form 
 
class findForm(forms.Form):
    #entry type choice field
    entry_type=forms.ChoiceField(label="Entry type:",choices=[['-1','Browse Entry Type...'],['0','Contacts'],['1','Calendar'],['2','Memos']],widget=forms.Select(attrs={'size':'1','selected':'-1','onchange':'addCombo()'}))
    #search key text box
    key=forms.CharField(initial='Search for pim...',label='',widget=forms.TextInput(attrs={'id':'AppRic','onkeyup':'load_data()','disabled':'disabled'}));
    #entry field choice
    entry_field=forms.ChoiceField(widget=forms.Select(attrs={'size':'1','selected':'-1'}))
    #entries per page choice field
    entries_per_page=forms.ChoiceField(label="Entries per page:",choices=[['5','5'],['10','10'],['15','15']],widget=forms.Select(attrs={'size':'1','selected':'-1','onchange':'paginateTable(\'tbResult\',0)','disabled':'disabled'}))
    ## @brief include media objects (js and css)
    class Media:
        css={
             'all': ('/media/css/appleFind.css',),
        }
        js=('/media/js/caption.js','/media/js/dynamic_combo.js','/media/js/create_table.js','/media/js/ajax.js','/media/js/paginate.js')
    


